Reuse React prop types as transient props with Styled Components
When passing props to a styled component, the prop name should be prefixed with a dollar sign ($) in order to turn it into a transient prop. This prevents props meant to be consumed by styled components from being passed to the underlying React node or rendered to the DOM element, which may cause unintented effects or invalid HTML.
However, nesting styled components in other components frequently leads to repetition of the same prop names over and over again, with the only difference being the mentioned dollar sign. Consider the following example, where the isActive
prop appears twice in TitleProps
and CardProps
. Managing more complex prop types can quickly become cumbersome.
|
|
We can remove this redundancy by implementing the PropsForStyling
utility type, which re-maps all keys of T
to be readonly, optional and start with the letter $
, as follows.
|
|
Technically, this type uses a combination of the following techniques (requiring TypeScript 4.1):
- Mapped Types that can create new object types based on arbitrary keys or other object types, as we’re doing here.
- Mapping Modifiers are used to define the new property as
readonly
andoptional
. - Key Remapping using the
as
clause, which allows to change property names of object types. - Template Literal Types that are similar to template literal strings in JavaScript, but are used in type positions. Here, we leverage them to add the dollar sign to the property name.
Using the PropsForStyling
type, we can rewrite the example from above without repetition.
|
|
Moreover, the types of all props of the parent component are now available on the nested styled component as well (you need to remember to pass their values, though). Arguably using this technique creates a very tight coupling between the components, which might not be desireable in all situations.